<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="AddRoleDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级 -->
              <el-col :span="19">
                <!-- 通过for循环 渲染二级权限 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRoleById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <el-tree
        :data="rightsList"
        :props="treeProps"
        ref="treeRef"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="AddRoleDialogVisible"
      width="40%"
      @close="addRoleDialogClosed"
    >
      <el-form
        :model="addRoleForm"
        ref="addRoleFormRef"
        :rules="addRoleFormRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRoleDialogVisible"
      width="40%"
      @close="editRoleDialogClosed"
    >
      <el-form
        :model="editRoleForm"
        ref="editRoleFormRef"
        :rules="editRoleFormRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  mounted() {},
  data() {
    return {
      rights: [
        {
          id: 101,
          authName: "基本权限",
          level: "0",
          pid: 0,
          desc: "普通党员一级权限",
        },
        {
          id: 103,
          authName: "缴费权限",
          level: "1",
          pid: 101,
          desc: "普通党员缴费权限",
        },
        {
          id: 105,
          authName: "缴费党费",
          level: "2",
          pid: 103,
          desc: "普通党员每月缴纳党费",
        },
        {
          id: 102,
          authName: "高级权限",
          level: "0",
          pid: 0,
          desc: "支部领导一级权限",
        },
        {
          id: 104,
          authName: "缴费权限",
          level: "1",
          pid: 102,
          desc: "支部领导缴费权限",
        },
        {
          id: 106,
          authName: "缴纳党费",
          level: "2",
          pid: 104,
          desc: "支部领导每月缴纳党费",
        },
        {
          id: 108,
          authName: "查询权限",
          level: "1",
          pid: 102,
          desc: "支部领导查询权限",
        },
        {
          id: 110,
          authName: "查询个人缴费记录权限",
          level: "2",
          pid: 108,
          desc: "支部领导查询支部党费个人缴费记录权限",
        },
        {
          id: 112,
          authName: "查询支部缴费记录权限",
          level: "2",
          pid: 108,
          desc: "支部领导查询支部每月缴费记录权限",
        },
      ],
      // 所有角色列表
      //   rolesList: [
      //     {
      //         "id": 30,
      //         "roleName": "普通党员",
      //         "roleDesc": "普通党员",
      //         "children": [
      //             {
      //                 "id": 101,
      //                 "authName": "基本权限",
      //                 "desc": "普通党员一级权限",
      //                 "children": [
      //                     {
      //                         "id": 103,
      //                         "authName": "缴费权限",
      //                         "desc": "普通党员缴费权限",
      //                         "children": [
      //                             {
      //                                 "id": 105,
      //                                 "authName": "缴费党费",
      //                                 "desc": "普通党员每月缴纳党费"
      //                             }
      //                         ]
      //                     }
      //                 ]
      //             }
      //         ]
      //     },
      //     {
      //         "id": 31,
      //         "roleName": "支部领导",
      //         "roleDesc": "支部领导",
      //         "children": [
      //             {
      //                 "id": 102,
      //                 "authName": "高级权限",
      //                 "desc": "支部领导一级权限",
      //                 "children": [
      //                     {
      //                         "id": 104,
      //                         "authName": "缴费权限",
      //                         "desc": "支部领导缴费权限",
      //                         "children": [
      //                             {
      //                                 "id": 106,
      //                                 "authName": "缴费党费",
      //                                 "desc": "支部领导每月缴纳党费"
      //                             }
      //                         ]
      //                     },
      //                     {
      //                         "id": 108,
      //                         "authName": "查询权限",
      //                         "desc": "支部领导查询权限",
      //                         "children": [
      //                             {
      //                                 "id": 110,
      //                                 "authName": "查询个人缴费记录权限",
      //                                 "desc": "支部领导查询支部党费个人缴费记录权限"
      //                             },
      //                             {
      //                                 "id": 112,
      //                                 "authName": "查询支部缴费记录权限",
      //                                 "desc": "支部领导查询支部每月缴费记录权限"
      //                             }
      //                         ]
      //                     }
      //                 ]
      //             }
      //         ]
      //     }
      // ],
      rolesList: [],
      // 分配权限框
      setRightDialogVisible: false,
      // 权限列表
      rightsList: [],
      //  树形控件的属性绑定对象
      treeProps: {
        label: "authName",
        children: "children",
      },
      //   默认选中节点ID值
      defKeys: [],
      //   添加用户对话框
      AddRoleDialogVisible: false,
      // 添加角色表单
      addRoleForm: {},
      //   添加角色表单验证
      addRoleFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      //   编辑角色信息
      editRoleForm: {
        id: "",
        roleName: "",
        roleDesc: "",
      },
      editRoleDialogVisible: false,
      editRoleFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      //当前即将分配权限的role
      role: "",
      //分配权限发送的数据
      roleFrom: {
        id:"",
        rights:""
      },
      //删除角色的id
      removeid: {
        id: "",
      },
      //编辑角色的id
      editid: {
        id: "",
      },
      //分配角色权限的id
      disid: {
        id: "",
      },
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    handleRights(templist) {
      //var templist = this.rights;
      console.log(templist);
      var level0rights = [];
      var level1rights = [];
      var level2rights = [];
      for (var i = 0; i < templist.length; i++) {
        if (templist[i].level == 0) {
          var temp = templist[i];
          temp.children = [];
          level0rights.push(temp);
          //console.log(level0rights);
        }
      }
      for (var i = 0; i < templist.length; i++) {
        if (templist[i].level == 1) {
          var temp = templist[i];
          temp.children = [];
          level1rights.push(temp);
          //console.log(level1rights);
        }
      }
      for (var i = 0; i < templist.length; i++) {
        if (templist[i].level == 2) {
          level2rights.push(templist[i]);
          //console.log(level2rights);
        }
      }

      for (var i = 0; i < level2rights.length; i++) {
        for (var j = 0; j < level1rights.length; j++) {
          if (level2rights[i].pid == level1rights[j].id) {
            level1rights[j].children.push(level2rights[i]);
          }
        }
      }
      //console.log(level1rights);

      for (var i = 0; i < level1rights.length; i++) {
        for (var j = 0; j < level0rights.length; j++) {
          if (level1rights[i].pid == level0rights[j].id) {
            level0rights[j].children.push(level1rights[i]);
          }
        }
      }
      //console.log(level0rights);
      return level0rights;
      //this.rightsList = level0rights;
    },
    async getRightsList() {
      const { data: res } = await this.$http.get("rightList");
      console.log(res);
      this.rights = res;
    },
    async getRolesList() {
      const { data: res } = await this.$http.get("roleList");
      console.log(res);
      this.rolesList = res;
    },
   
    // 分配权限
    showSetRightDialog(role) {
      console.log(role);
      this.role = role;
      this.getRightsList();
      this.rightsList = this.handleRights(this.rights);
      //   递归获取三级节点的id
      if (role.children[0] === undefined) {
        this.setRightDialogVisible = true;
      } else {
        this.getLeafkeys(role.children[0], this.defKeys);
        console.log(this.defKeys);
        this.setRightDialogVisible = true;
      }
    },
    // 通过递归 获取角色下三级权限的 id, 并保存到defKeys数组
    getLeafkeys(node, arr) {
      console.log(node);
      //console.log(node.id);
      //children属性长度为0，则是三级节点
      if (node.children.length==0) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getLeafkeys(item, arr));
    },
    // 权限对话框关闭事件
    setRightDialogClosed() {
      this.defKeys = [];
    },
    // 添加角色对话框的关闭
    addRoleDialogClosed() {
      this.$nextTick(() => {
        if (this.$refs.addRoleForm !== undefined)
          this.$refs.addRoleForm.resetFields();
      });
    },
    // 编辑角色对话框的关闭
    editRoleDialogClosed() {
      this.$nextTick(() => {
        if (this.$refs.editRoleForm !== undefined)
          this.$refs.editRoleForm.resetFields();
      });
    },
    // 添加角色
    addRoles() {
      this.$refs.addRoleFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "addRole",
          this.$qs.stringify(this.addRoleForm)
        );
        this.$message.success("添加角色成功！");
        this.AddRoleDialogVisible = false;
        this.getRolesList();
      });
    },
    // 删除角色
    async removeRoleById(id) {
      console.log(id);
      const confirmResult = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      this.removeid.id = id;
      const { data: res } = await this.$http.post(
        "deleteRole",
        this.$qs.stringify(this.removeid)
      );
      //if (res.meta.status !== 200) return this.$message.error("删除角色失败！");
      this.$message.success("删除用户成功！");
      this.getRolesList();
    },
    // 编辑角色
    async showEditDialog(id) {
      this.editid.id = id;
      const { data: res } = await this.$http.post(
        "queryRole",
        this.$qs.stringify(this.editid)
      );
      console.log(res);
      this.editRoleForm.id = res.id;
      this.editRoleForm.roleName = res.roleName;
      this.editRoleForm.roleDesc = res.roleDesc;
      this.editRoleDialogVisible = true;
    },
    editRoles() {
      this.$refs.editRoleFormRef.validate(async (valid) => {
        // console.log(valid)
        // 表单预校验失败
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "updateRole",
          this.$qs.stringify(this.editRoleForm)
        );
        // 隐藏编辑角色对话框
        this.editRoleDialogVisible = false;
        this.$message.success("更新角色信息成功！");
        this.getRolesList();
      });
    },
    // 分配权限
    async allotRights() {
      // 获得当前选中和半选中的Id
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      console.log(this.role);
      console.log(keys);
      //将id对应的权限取出并结构化。
      var temprights = [];
      for (var i = 0; i < keys.length; i++) {
        for (var j = 0; j < this.rights.length; j++) {
          if (keys[i] == this.rights[j].id) {
            temprights.push(this.rights[j]);
          }
        }
      }

      temprights = this.handleRights(temprights);
      this.role.children = temprights;
      this.roleFrom.id = this.role.id;
      console.log(this.roleFrom);
      // join() 方法用于把数组中的所有元素放入一个字符串
        const idStr = keys.join(",");
        this.roleFrom.rights=idStr;
      // console.log(this.roleFrom);
      console.log(this.roleFrom);
      // console.log(idStr);
      const { data: res } = await this.$http.post(
        "updateRoleRights",
        this.$qs.stringify(this.roleFrom)
      );
      this.$message.success("分配权限成功!");
      this.getRolesList();
      this.setRightDialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
